package com.eight.cloud.auth.common.config;

import cn.hutool.core.util.ObjectUtil;
import com.eight.cloud.auth.model.vo.CurrentUser;
import com.eight.cloud.core.global.model.LoginUser;
import com.eight.cloud.openfeign.admin.api.UserClient;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * bean配置
 *
 * @ClassName: BeanConfig
 * @Author: TXC
 * @Date: 2024-10-08 21:20
 **/
@Component
public class BeanRegistrar {

    @Resource
    private UserClient userClient;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return username -> {
            LoginUser loginUser = userClient.getUserinfo(username, null);
            if (ObjectUtil.isNull(loginUser)) {
                throw new UsernameNotFoundException("用户不存在");
            }
            return new CurrentUser(loginUser);
        };
    }
}
